<template>
  <!-- 位置栏 -->
  <div class="table-container">
    <div class="navigation">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>基础组件</el-breadcrumb-item>
        <el-breadcrumb-item>表格</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-input v-model="searchForm.name" placeholder="姓名" class="search-input" clearable></el-input>
      <el-select v-model="searchForm.gender" placeholder="性别" class="search-select" clearable>
        <el-option disabled label="" value="">Please select one</el-option>
        <el-option label="男" value="男"></el-option>
        <el-option label="女" value="女"></el-option>
      </el-select>
      <el-input v-model="searchForm.city" placeholder="城市" class="search-input" clearable></el-input>
      <el-input v-model="searchForm.address" placeholder="地址" class="search-input" clearable></el-input>
      <el-button :icon="Search" @click="onSearch" class="search-button" circle></el-button>
      <el-button link type="primary" @click="onClear" class="search-button">清空</el-button>
      <el-button link type="primary" @click="handleCreate" class="search-button">新增</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table-wrapper">
      <el-table :data="tableData" class="gridTable" v-loading="loading">
        <el-table-column prop="name" label="姓名" width="100"></el-table-column>
        <el-table-column prop="gender" label="性别" width="100"></el-table-column>
        <el-table-column prop="city" label="城市" width="100"></el-table-column>
        <el-table-column prop="address" label="地址" min-width="200"></el-table-column>
        <el-table-column prop="date" label="注册日期" width="100"></el-table-column>
        <el-table-column fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">Edit</el-button>
            <el-button link type="primary" size="small" @click="handleDelete(scope.$index, scope.row)">Delete
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页栏 -->
    <div class="pagination-container">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageTotal"
      />
    </div>
    <!-- 编辑弹出框 -->
    <el-dialog :title="tilte" v-model="dialogShow" width="30%">
      <el-form label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="form.address"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
      <span class="dialog-footer">
          <el-button @click="dialogShow = false">取 消</el-button>
          <el-button type="primary" @click="editConfirm">确 定</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, computed, watch, reactive, onMounted} from 'vue'
import {fetchData} from "../../api";
import {ElMessage, ElMessageBox} from "element-plus";
import {Search} from '@element-plus/icons-vue';
import router from "@/router";
import RegionTree from "../tree/DeptTree.vue";

const loading = ref(true)
const tableData = ref([]);
const currentPage = ref(1);
const pageTotal = ref(0);

//搜索数据
const searchForm = ref({
  name: '',
  gender: '',
  city: '',
  address: ''
});

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

//获取表格数据
onMounted(() => {
  fetchData(searchForm).then((response) => {
    tableData.value = response.list;
    pageTotal.value = response.pageTotal;
  })
  sleep(1000).then(() => loading.value = false)
})

//点击搜索
const onSearch = () => {
  loading.value = true;
  fetchData(searchForm).then((response) => {
    tableData.value = response.list.filter(item => {
      return (
          (!searchForm.value.name || item.name.includes(searchForm.value.name)) &&
          (!searchForm.value.gender || item.gender === searchForm.value.gender) &&
          (!searchForm.value.city || item.city.includes(searchForm.value.city)) &&
          (!searchForm.value.address || item.address.includes(searchForm.value.address))
      )
    })
    pageTotal.value = response.pageTotal;
    sleep(1000).then(() => loading.value = false)
  });
};

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return tableData.value.slice(start, end);
});

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
};


//清空搜索
const onClear = () => {
  searchForm.value = {};
  currentPage.value = 1; // 重置到第一页
};

//弹窗数据
let form = reactive({
  title: "",
  name: "",
  address: "",
});

//表格编辑时弹窗和保存
let tilte = "";
const dialogShow = ref(false);

//点击新增
const handleCreate = () => {
  router.push('/form')
  /*tilte = "新增";
  dialogShow.value = true;
  form.value = {};*/
};

//点击编辑
let idx = -1;
const handleEdit = (index, row) => {
  tilte = "编辑";
  idx = index;
  Object.keys(form).forEach((item) => {
    form[item] = row[item];
  });
  dialogShow.value = true;
};

//点击确认
const editConfirm = () => {
  if (tilte === "新增") {
    dialogShow.value = false;
    ElMessage.success("新增成功");
    console.log(form);
    tableData.value.push(form)
  } else {
    dialogShow.value = false;
    ElMessage.success(`修改第 ${idx + 1} 行成功`);
    Object.keys(form).forEach((item) => {
      tableData.value[idx][item] = form[item];
    });
  }
};

// 删除操作
const handleDelete = (index, row) => {
  // 二次确认删除
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    type: "warning",
  }).then(() => {
    ElMessage.success("删除成功");
    tableData.value.splice(index, 1);
  }).catch(() => {
    //ElMessage.success("删除失败");
  });
};

watch(searchForm, () => {
  onSearch();
});

</script>

<style scoped>
.table-container {

}

.search-container {
  border: 1px dashed #ccc;
}

.table-wrapper {
  height: calc(100vh - 280px);
  border: 1px dashed red;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}

.navigation {
  padding: 5px;
  border: 1px dashed #ccc;
}

.search-button {
  margin: 5px 5px;
}

.search-input {
  margin: 5px 5px;
  max-width: 200px;
}

.search-select {
  margin: 5px 5px;
  width: 100px;
}

.gridTable {
  width: 100%;
  height: 100%;
  max-width: 100%; /* 确保容器宽度不超过浏览器窗口 */
  overflow: auto;
  border: 1px dashed #ccc;
  background-color: #cccccc;
}

</style>